 'use strict'

var rs = require('./redis_service')
var db = require('./mysql_service')
var errs = require('restify-errors')
var validators = require('./validators')

//获取每天的股票个数
exports.get_count = function (args, res) {
  var date = args.date;
  var cnt = args.count;
  if (!validators.isValidDateString(date)) {
    res.json(new errs.BadRequestError('非法的请求，请输入合法的{date}'))
  } else if (!validators.isValidCountString(cnt)) {
    res.json(new errs.BadRequestError('非法的请求，请输入合法的{count}'))
  } else {
    let key = `stock_count_${date}_${cnt}`
    let exists = false
    rs.get(key)
      .then(data => {
        if (data === null) {
          return db.getCount(date,cnt)
        } else {
          exists = true
          return data
        }
      }).then(data => {
        if (!exists) {
          rs.set(key, data)
        }
        res.json(data)
      }).catch(e => {
        console.log(e)
        res.json(500, {
          code: e.name,
          message: e.message
        })
      })
  }
}

//获取股票
exports.get_stock = function(args, res) {
  var date = args.date;
  var type = args.type;
  if (!validators.isValidDateString(date)) {
    res.json(new errs.BadRequestError('非法的请求，请输入合法的{date}'))
  }else if (!validators.isValidClassType(type)) {
    res.json(new errs.BadRequestError('非法的请求，请输入合法的{type}'))
  }else {
    let key = `stock_${date}_${type}`
    let exists = false
    rs.get(key)
    .then(data =>{
      if (data ===null) {
        return db.getStock(date, type)
      } else {
        exists = true
        return data
      }
    }).then(data => {
      if (!exists) {
        rs.set(key, data)
      }
      res.json(data)
    }).catch(e => {
      console.log(e)
      res.json(500, {
        code: e.name,
        message: e.message
      })
    })
  }
}
